import { Component, ViewChild } from '@angular/core';

import { Storage } from '@ionic/storage';

import { Events, AlertController, ModalController, NavController, NavParams, ActionSheetController, Content } from 'ionic-angular';

import { Config } from '../../../../providers/config';

import { Common } from '../../../../providers/common';

import _ from 'lodash';
import {MarketingDailyListService} from "./list.service";
import {MarketingDailyDetailPage} from "../detail/detail.component";
import {MarketingDailyQueryPage} from "../query/query.component";

import {MarketingDailySavePage} from "../save/save.component";
import {MarketingDailyCollectPage} from "../collect/collect.component";

@Component({
  selector: 'page-marketing-daily-list',
  templateUrl: './list.html',
  providers: [MarketingDailyListService]
})
export class MarketingDailyListPage {
	moa_page_name: any = "page-marketing-daily-list";
  moa_page_explain: any = "工作日报";

  @ViewChild(Content) content: Content;

  // 列表数据
  listData: any = [];
  //显示标题
  title = '';

  _ = _;
  // 页码
  pageIndex = 1;
  // 是否加载更多
  isLoadMore = true;

  keyWord = "";
  //
  queryCondition = null;

  //是否显示选择框
  isShowCheck = false;

  defaultEmpByTree = [];

  constructor(
    public alertCtrl: AlertController,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    private navParams: NavParams,
    public events: Events,
    public config: Config,
    public storage: Storage,
    public common: Common,
    public listService: MarketingDailyListService,
    public actionSheetCtrl: ActionSheetController
    ) {

    this.storage.remove("advancedQueryCondition");
    this.isShowCheck = this.navParams.get("showCheck") && true;

    if(this.isShowCheck){
      //获取用户信息
      this.storage.get('userInfo').then((userInfo) => {
        if (userInfo) {
          this.initQueryCondition();
          this.queryCondition.emp = "'" + userInfo.emname + "'";
          // 初始化数据
          this.loadListData(this.pageIndex, null, null);
        }
      });
    }else{
      this.initQueryCondition();

      // 初始化数据
      this.loadListData(this.pageIndex, null, null);
    }
  }


  /**
   * [loadListData 加载列表数据]
   * @param {[type]} page           [页码]
   * @param {[type]} infiniteScroll [加载更多组件]
   * @param {[type]} refresher      [下拉刷新组件]
   */
   loadListData(page, infiniteScroll, refresher) {
     console.log('this.queryCondition');
     console.log(this.queryCondition);
     this.listService.getListData(page, this.queryCondition).subscribe(data => {
       if (data) {
         var dataList = [];
         _.forEach(data, function (i) {
           let d = i.split("|");
           console.log(d);
           d.push(false);
           if (d[13] != "") {
             let temp = d[13].split("/");
             d[13] = temp[1];
             d.push(temp[0]);
           } else {
             d.push("");
           }
           dataList.push(d);
         });
         console.info(data);
         // 如果加载第一页，则清空数据
         if (page == 1) {
           this.isLoadMore = true;
           this.listData = [];
         }
         // 把现有数据和新加载的数据合并
         this.listData = _.concat(this.listData, dataList);
         // 增加搜索索引
         this.pageIndex = this.pageIndex + 1;

         // 如果返回数据少于请求页数，则不再加载更多
         if (data.length < this.config.pageSize) {
           this.isLoadMore = false;
         }
       } else {
         if (this.pageIndex == 1) {
           this.listData = [];
         }
         // this.listData = [];
         this.isLoadMore = false;
       }
       // complete event
       if (infiniteScroll) {
         infiniteScroll.complete();
       }
       if (refresher) {
         refresher.complete();
       }
     })
   }
  /**
   * [goDetailPage 跳转详情页]
   * @param {[type]} item [参数]
   */
   goDetailPage(item) {
     console.log("----------");
     console.info(item);
     if(!this.isShowCheck){
       this.navCtrl.push(MarketingDailyDetailPage, {
         "detail" : item
       });
     }else{
       //选择模式
     }
   }
   ionViewDidLoad() {
     console.log(new Date());
   }

   ionViewDidEnter() {
     this.storage.get("doRefresh").then(data => {
       if (data) {
         this.pageIndex = 1;
         this.loadListData(this.pageIndex, null, null);
         this.storage.remove("doRefresh");
       }
     })
   }

  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
   doInfinite(infiniteScroll) {
     if (this.pageIndex != 1) {
       console.info("-----------infiniteScroll------------");
       console.info(infiniteScroll);
       if (this.isLoadMore) {
         this.loadListData(this.pageIndex, infiniteScroll, null);
       } else {
         infiniteScroll.complete();
       }
     } else {
       infiniteScroll.complete();
     }
   }
  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
   doRefresh(refresher) {
     this.pageIndex = 1;
     this.isLoadMore = true;
     this.loadListData(this.pageIndex, null, refresher);
   }


   search() {
     let that = this;
     //console.log("##search 关键字：" + this.keyWord);
     this.content.scrollTo(0, 0, 100);
     this.initQueryCondition();
     this.pageIndex = 1;
     if (this.keyWord) {
       this.common.getContactNameByJianPin(this.keyWord, 0).then((dataList: string[]) => {
         console.log(dataList);
         if (dataList.length > 50) {
           let alert = this.alertCtrl.create({
             title: "提示",
             message: "模糊搜索匹配的员工数量太多，请重新输入。",
             buttons: [
               {
                 text: "确定",
                 role: 'cancel',
                 handler: () => {
                 }
               }
             ]
           });
           alert.present();
           return ;
         }
         let empString = "";
         _.forEach(dataList, d => {
           if (empString == "") {
             empString = _.toString(d);
           } else {
             empString += "," + d;
           }
         });
         console.log("empString" + empString);
         if (empString == "") {
           empString = "''";
         } else {
           empString = "'" + empString + "'";
         }
         that.queryCondition.emp = empString;
         that.loadListData(this.pageIndex, null, null);
         /*that.listService.getAllAuthority().subscribe(authList => {

         });*/
       });
     } else {
       this.queryCondition.emp = "'ALL'";
       this.loadListData(this.pageIndex, null, null);
     }
   }

   showAdvancedQueryModal() {
     let that = this;
     console.log("打开Modal");
     let queryModal = this.modalCtrl.create(MarketingDailyQueryPage, {

     });
     queryModal.onWillDismiss(data => {
       if (data && data != "close") {
         this.storage.get("advancedQueryCondition")
         .then(data => {
           if (data != null) {
             this.queryCondition = data;
             this.queryCondition.startdate.replace("-", "");
             this.queryCondition.enddate.replace("-", "");
             this.keyWord = "";
             this.pageIndex = 1;
             if (this.queryCondition.emp == "") {
               this.queryCondition.emp = "'ALL'";
               that.loadListData(this.pageIndex, null, null);
             } else {
               let dataList = this.queryCondition.emp.split(",");
               that.listService.getAllAuthority().subscribe(authList => {
                 console.log(dataList);
                 let empString = "";
                 _.forEach(dataList, d => {
                   let temp = _.result(_.find(authList, {"usr_nm": d}), "usr_nm");
                   if (temp) {
                     if (empString == "") {
                       empString = _.toString(temp);
                     } else {
                       empString += "," + temp;
                     }
                   }
                 });
                 if (empString == "") {
                   empString = "''";
                 } else {
                   empString = "'" + empString + "'";
                 }
                 that.queryCondition.emp = empString;
                 that.loadListData(this.pageIndex, null, null);
               });
             }
           }
         });
       }
     });
     queryModal.present();
   }

  cellectDailyRecord() {
    let that = this;
    console.log("打开Modal");
    let queryModal = this.modalCtrl.create(MarketingDailyCollectPage, {

    });
    queryModal.onWillDismiss(data => {

    });
    queryModal.present();
  }

   initQueryCondition() {
     this.queryCondition = {
       "emp" : "'ALL'",
       "cusname":"",
       "startdate" : (this.common.getDate(-30)).replace("-", ""),
       "enddate" : (this.common.getNowFormatDate()).replace("-", "")
     }
   }

   chooseListType() {
     let bottons = [{
       text: '新增工作日报',
       handler: () => {
         this.navCtrl.push(MarketingDailySavePage, {
           "isEdit": false
         });
       }
     }, {
       text: '高级查询',
       handler: () => {
         this.showAdvancedQueryModal();
       }
     }, {
       text: '工作日报汇总',
       handler: () => {
         this.cellectDailyRecord();
       }
     }, {
       text: '取消',
       role: 'cancel',
       handler: () => {
       }
     }];

     let actionSheet = this.actionSheetCtrl.create({
       title: '',
       buttons: bottons
     });
     actionSheet.present();
   };
  /*
  * 选择工作日报完成
  */
  chooseListDone(){
    //获取工作日报id
    let communtionids = [];
    _(this.listData).forEach(function(item) {
      if(item[item.length - 2]){
        let conn =[item[0],item[1],item[2],item[3],item[5],item[7],item[6],item[9],item[10],false,"false"];
        communtionids.push(conn);
      }
    })
    this.events.publish('weekly-edit-list:update', communtionids);
    this.navCtrl.pop();
  }

}


